package me.zhengjie.modules.mnprogram.rest;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.mnprogram.config.WxMaConfiguration;
import me.zhengjie.modules.mnprogram.domain.WxUser;
import me.zhengjie.modules.mnprogram.repository.WxUserRepository;
import me.zhengjie.modules.mnprogram.soup.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@AllArgsConstructor
@Slf4j
@Api(value = "微信获取信息接口", tags = "面经获取openid和sessionKey和登录获取用户相关接口")
@RequestMapping("/api")
public class WxApiController {


    @Autowired
    WxUserRepository wxUserRepository;


    private final WxMpService wxService;
    /**
     * 登陆接口
     */
    @GetMapping("/login")
    @ApiOperation(value = "获取openid和session")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "前端获取的code码")

    })
    @AnonymousAccess
    public WxMaJscode2SessionResult login(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(Constants.appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            return  session;
            //TODO 可以增加自己的逻辑，关联业务相关数据
            //return JsonUtils.toJson(session);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            //return e.toString();
        }
        return  null;
    }


    @ApiOperation("获取素材列表")
    @GetMapping("/material/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "offset", value = "起始位置默认为0"),
            @ApiImplicitParam(name = "position", value = "终点位置，默认为20"),

    })
    @AnonymousAccess
    public WxMpMaterialNewsBatchGetResult test(Integer offset,Integer position) throws WxErrorException {
        if (offset==null){
            offset=0;
        }
        if (position==null){
            position=20;
        }
        WxMpMaterialNewsBatchGetResult result= wxService.getMaterialService().materialNewsBatchGet(offset,position);
        return result;
    }
    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/info")
    @ApiOperation(value = "获取用户昵称等信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "微信openid"),
            @ApiImplicitParam(name = "gender", value = "性别"),
            @ApiImplicitParam(name = "encryptedData", value = "加密数据"),
            @ApiImplicitParam(name = "iv", value = "不知道啥东西"),
            @ApiImplicitParam(name = "location", value = "地址"),
            @ApiImplicitParam(name = "avatarUrl", value = "头像地址"),
            @ApiImplicitParam(name = "sessionKey", value = "回话Key,login接口传过来的v")

    })
    @AnonymousAccess
    public WxUser info(String openid, Integer gender, String encryptedData,
                       String iv, String location,
                       String avatarUrl, String sessionKey) {

        log.error(avatarUrl);
        final WxMaService wxService = WxMaConfiguration.getMaService(Constants.appid);
        WxUser userdb = wxUserRepository.findUserByOpenid(openid);
        if (userdb==null){
          userdb = new WxUser();
          // 解密用户信息
          WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
          WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
          userdb.setOpenid(openid);
          userdb.setLocation(location);
          BeanUtils.copyProperties(userInfo,userdb);
          userdb.setPhoneNumber(phoneNoInfo.getPhoneNumber());
          userdb.setGender(gender);
          userdb.setId(UUID.randomUUID().toString());
            wxUserRepository.save(userdb);
        }
        return userdb;

    }

}
